<template>
  <div class="login-box">
    <!-- logo -->
    <!-- 描述文案 -->
    <div class="login_content">
      <div class="content_info">
        <img src="@/assets/images/login-logo.png" alt="" class="login_logo" />
        <div class="info_title1">会通新材料股份有限公司</div>
        <div class="info_title">合肥工厂能源管理平台</div>
        <!-- <img src="@/assets/images/login-text.png" alt="" class="ifno_desc" /> <br /> -->
        <!-- <img src="@/assets/images/login-text-login.png" alt="" class="ifno_logo" /> -->
      </div>
    </div>
    <!-- 登录表单 -->
    <div class="login_form">
      <div class="form_box">
        <div class="form_container">
          <div class="form_title">账号登录</div>
          <el-form ref="formRef" :model="formValue" :rules="formRules" label-position="top">
            <el-form-item label="账号" prop="account">
              <div class="form_item">
                <el-input v-model="formValue.account" placeholder="请输入账号" />
              </div>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <div class="form_item">
                <el-input type="password" v-model="formValue.password" placeholder="请输入密码" show-password />
              </div>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
              <div class="form_item">
                <el-input v-model="formValue.code" maxlength="4" placeholder="请输入验证码" />
                <img :src="codeValue.codeImg" alt="" class="form_code" @click="commEvent.getCodeValue" />
              </div>
            </el-form-item>
          </el-form>
          <div class="form_foot">
            <el-button type="primary" :loading="loading" @click="commEvent.onSubmit" class="foot_btn">登&emsp;录</el-button>
          </div>
        </div>
        <div class="form_mask"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue"
import { ElMessage } from "element-plus"
import { FormInstance, FormRules } from "element-plus"
import { encryptDes } from "@/utils/des"
import { initDynamicRouter } from "@/routers/modules/dynamicRouter"
import { useUserStore } from "@/stores/modules/user"
import { useTabsStore } from "@/stores/modules/tabs"
import { useAuthStore } from "@/stores/modules/auth"
import { useRouter } from "vue-router"
import { useKeepAliveStore } from "@/stores/modules/keepAlive"
import { getCodeApi, loginApi } from "@/api/modules/login"
// 参数
const userStore = useUserStore()
const tabsStore = useTabsStore()
const keepAliveStore = useKeepAliveStore()
const router = useRouter()
const formRef = ref<FormInstance>() // 表单实例
const loading = ref<boolean>(false) // 加载状态
// 表单数据
const formValue = ref({
  account: "",
  password: "",
  code: ""
})
// 验证码信息
const codeValue = ref({
  codeImg: "",
  uuid: ""
})
// 表单校验
const formRules: FormRules = {
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
}

// 事件
const commEvent = {
  // 获取验证码信息
  getCodeValue: async () => {
    const { data } = await getCodeApi()
    const { codeImg, uuid } = data
    codeValue.value = { codeImg: "data:image/png;base64," + codeImg, uuid }
  },
  // 登录
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      const params = { ...formValue.value, password: encryptDes(formValue.value.password), uuid: codeValue.value.uuid }
      loading.value = true
      const { data } = await loginApi(params).finally(() => {
        loading.value = false
      })
      const info = { ...data.user, roleList: data.roleList, deptList: data.deptList }
      userStore.setUserInfo(info)
      userStore.setToken(data.token)
      // 添加动态路由
      await initDynamicRouter()
      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([])
      keepAliveStore.setKeepAliveName([])
      const authStore = useAuthStore()
      const { authMenuList } = authStore
      const hasScreen = authMenuList.find(e => e.path === "/home" && !e.meta.isHide)
      if (hasScreen) {
        router.replace("/home")
      } else {
        const firstPath = commEvent.findFirstPath(authMenuList)
        if (firstPath) {
          router.replace(firstPath)
        } else {
          ElMessage.error("当前角色未配置有效路径")
        }
      }
    })
  },
  // 递归寻找第一个有效路径
  findFirstPath: (menus: Menu.MenuOptions[]): string | null => {
    for (const item of menus) {
      // 如果组件为Layout 或未设置组件 或未设置路径 或隐藏，尝试子菜单
      if (item.component === "Layout" || !item.component || !item.path || item.meta.isHide) {
        if (item.children && item.children.length > 0) {
          const result = commEvent.findFirstPath(item.children)
          if (result) return result
        }
      } else {
        return item.path
      }
    }
    return null
  }
}
onMounted(() => {
  // 清除首次登录修改密码的token
  userStore.setPasswordToken("")
  commEvent.getCodeValue()
  // 监听键盘 enter 事件
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return
      commEvent.onSubmit()
    }
  }
})
</script>

<style lang="scss" scoped>
.login-box {
  position: relative;
  display: flex;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-image: url("@/assets/images/login-background.png");
  background-repeat: no-repeat;
  background-size: cover;
  .login_logo {
    position: absolute;
    top: 30px;
    left: 50px;
    width: 200px;
  }
  .login_content {
    display: flex;
    flex: 1;
    // align-items: center;
    margin-top: 5%;
    .content_info {
      margin-left: 50px;
      .info_title1 {
        font-size: 26px;
        font-weight: 700;
        color: #d5f8ff;
      }
      .info_title {
        font-size: 48px;
        font-weight: 700;
        color: #d5f8ff;
      }
      .ifno_desc {
        width: 380px;
        margin-top: 10px;
      }
      .ifno_logo {
        width: 220px;
        margin-top: 20px;
      }
    }
  }
  .login_form {
    position: relative;
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    min-width: 500px;
    .form_box {
      position: relative;
      width: 410px;
      .form_container {
        box-sizing: border-box;
        width: 100%;
        padding: 30px;
        background-color: #ffffff;
        border-radius: 23px;
        .form_title {
          width: 100%;
          margin-bottom: 20px;
          font-size: 18px;
          font-weight: bold;
          color: #111111;
        }
        .form_item {
          display: flex;
          align-items: center;
          width: 100%;
          height: 40px;
          background-color: #f7f8fa;
          :deep(.el-input__wrapper) {
            background-color: #f7f8fa;
            box-shadow: none;
          }
          .form_code {
            height: 35px;
          }
        }
        .form_foot {
          display: flex;
          justify-content: center;
          width: 100%;
          margin-top: 50px;
          .foot_btn {
            width: 100%;
            height: 40px;
            font-size: 18px;
            box-shadow: 5px 5px 10px #00000040;
          }
        }
      }
      .form_mask {
        position: absolute;
        width: 90%;
        height: 40px;
        margin-top: -20px;
        margin-left: 5%;
        background-color: #ffffff;
        border-radius: 23px;
        opacity: 0.3;
      }
    }
  }
}
</style>
